package com.blue.Impl.system;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.blue.common.constant.CommonConstant;
import com.blue.mapper.system.GenerateMapper;
import com.blue.po.system.DataSyncInfoPO;
import com.blue.po.system.SyncFailDetailPO;
import com.blue.service.system.IDataSyncInfoService;
import com.blue.service.system.IDataSyncService;
import com.blue.service.system.ISyncFailDetailService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.blue.mapper.system.DataSyncConfMapper;
import com.blue.po.system.DataSyncConfPO;
import com.blue.service.system.IDataSyncConfService;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.baomidou.mybatisplus.core.toolkit.StringPool.ASTERISK;


@Service
@Slf4j
public class DataSyncConfServiceImpl extends ServiceImpl<DataSyncConfMapper, DataSyncConfPO> implements IDataSyncConfService {

    @Autowired
    private IDataSyncService dataSyncService;

    @Override
    public void syncData(String tableName) {
        //判断今天时间类型
        List<String> frequencyList = new ArrayList<>();
        //每日
        frequencyList.add(CommonConstant.DAILY);
        Calendar calendar = Calendar.getInstance();
        // 判断是否为周一
        if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) {
            frequencyList.add(CommonConstant.MONDAY);
        }
        // 判断是否为月初
        if (calendar.get(Calendar.DAY_OF_MONTH) == 1) {
            frequencyList.add(CommonConstant.BEGIN_OF_MONTH);
        }
        log.info("同步时间类型为:{}", frequencyList);
        //获取数据同步配置信息
        LambdaQueryWrapper<DataSyncConfPO> queryWrapper = new LambdaQueryWrapper<DataSyncConfPO>()
                .eq(DataSyncConfPO::getStatus, CommonConstant.NORMAL);
        if (StringUtils.isNotBlank(tableName)) {
            queryWrapper.eq(DataSyncConfPO::getTableNm, tableName);
        } else {
            queryWrapper.in(DataSyncConfPO::getFrequency, frequencyList);
        }
        List<DataSyncConfPO> dataSyncConfPOS = this.list(queryWrapper);
        log.info("需要同步的数据同步配置数量为:{}", dataSyncConfPOS.size());
        //依次同步每个配置信息的数据(异步处理)
        dataSyncConfPOS.forEach(item -> dataSyncService.dataSync(item));
    }
}
